<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog"
      :class="{ readonly: readOnly }"
      :custom-class="'panna-dialog_medium'"
      title="现场采样记录单"
      align="center"
      :visible.sync="innerDialogFormVisible"
      @closed="closeDialog"
    >
      <el-form
        ref="formData"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="被采样单位"
              :label-width="formLabelWidth"
              prop="samplingUnitName"
              :error="errorMsg.samplingUnitName"
            >
              <el-input
                v-model="formData.samplingUnitName"
                :disabled="readOnly"
              ></el-input>
              <div v-if="!readOnly" class="addCustomer" @click="addUnit">+</div>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item
              label="采样地点"
              :label-width="formLabelWidth"
              :error="errorMsg.samplingPositionId"
            >
              <el-select
                v-model="formData.samplingPositionId"
                placeholder="请选择"
                :disabled="readOnly"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.position"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item
              label="负责人"
              :label-width="formLabelWidth"
              :error="errorMsg.principalPeople"
            >
              <el-input
                v-model="formData.principalPeople"
                :disabled="readOnly"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="采样人"
              :label-width="formLabelWidth"
              prop="samplingPeople"
              :error="errorMsg.samplingPeople"
            >
              <el-input
                v-model="formData.samplingPeople"
                :disabled="readOnly"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="采样时间"
              :label-width="formLabelWidth"
              prop="samplingDateTime"
              :error="errorMsg.samplingDateTime"
            >
              <el-date-picker
                v-model="formData.samplingDateTime"
                :disabled="readOnly"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          label="采样目的"
          :label-width="formLabelWidth"
          :error="errorMsg.samplingPurpose"
        >
          <el-input
            v-model="formData.samplingPurpose"
            :disabled="readOnly"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="采样设备"
          :label-width="formLabelWidth"
          :error="errorMsg.samplingEquipment"
        >
          <el-input
            v-model="formData.samplingEquipment"
            :disabled="readOnly"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="5">
            <el-form-item
              label="采样样品"
              :label-width="formLabelWidth"
              prop="samplingSamples"
            >
              <el-button
                v-if="!readOnly"
                icon="el-icon-plus"
                type="primary"
                plain
                @click="addSamplingSample"
                >新增</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          v-for="(item, index) in formData.samplingSamples"
          :key="index"
          style="margin-bottom: 10px"
        >
          <el-card class="box-card">
            <div style="float: right">
              <el-link
                v-if="!readOnly"
                size="mini"
                type="danger"
                @click="delSamplingSample(index)"
                >删除</el-link
              >
            </div>
            <br />
            <br />
            <div>
              <el-form
                label-width="100px"
                :model="formData.samplingSamples[index]"
                status-icon
              >
                <el-row>
                  <el-col :span="8">
                    <el-form-item
                      label="样品编号"
                      :label-width="formLabelWidth"
                    >
                      <el-input
                        v-model="
                          formData.samplingSamples[index].samplingSampleNum
                        "
                        :disabled="readOnly"
                        autocomplete="off"
                        @change="
                          samplingSampleNumChange(
                            index,
                            formData.samplingSamples[index].samplingSampleNum
                          )
                        "
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      label="样品名称"
                      :label-width="formLabelWidth"
                    >
                      <el-input
                        v-model="
                          formData.samplingSamples[index].smaplingSampleName
                        "
                        :disabled="readOnly"
                        autocomplete="off"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      label="样品数量"
                      :label-width="formLabelWidth"
                    >
                      <el-input
                        v-model="
                          formData.samplingSamples[index].samplingSampleCount
                        "
                        :disabled="readOnly"
                        autocomplete="off"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item
                      label="采样地点"
                      :label-width="formLabelWidth"
                    >
                      <el-input
                        v-model="
                          formData.samplingSamples[index].samplingPosition
                        "
                        :disabled="readOnly"
                        autocomplete="off"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-card>
        </el-row>
        <el-form-item
          label="被采样物品或者场所情况"
          :label-width="formLabelWidth"
          :error="errorMsg.samplingRemark"
        >
          <el-input
            v-model="formData.samplingRemark"
            :disabled="readOnly"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <div v-if="!readOnly" slot="footer" class="dialog-footer" align="center">
        <el-button
          :disabled="!submitLoad"
          type="primary"
          @click="submit('formData')"
          >提 交</el-button
        >
        <el-button
          :disabled="!submitLoad"
          style="width: 100px"
          type="primary"
          @click="draftSubmit"
          >保 存 草 稿</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
      <ChoiceSamlingUnitDialog
        v-if="chioceDialogVisible"
        :chioce-dialog-visible.sync="chioceDialogVisible"
        @colseSamplingSample="colseSamplingSample"
      />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
import { create, update, get } from "../../../api/Sampling/SamplingSingle.js";
// import {
//   GetSamplingSampleNum,
//   GetSamplingSampleNumByNewNum,
// } from "../../../api/Sampling/SamplingSample.js";
import ChoiceSamlingUnitDialog from "../../../components/SamplingManage/ChoiceSamlingUnitDialog.vue";
export default {
  name: "SamplingSingleEdit",
  components: { ChoiceSamlingUnitDialog },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      unitName: "",
      innerDialogFormVisible: false,
      chioceDialogVisible: false,
      loading: false,
      submitLoad: true,
      options: [],
      // 存入样品编号判断是否有变化
      sampleNum: [],
      formLabelWidth: "100px",
      initData: {
        id: 0,
        samplingUnitName: "",
        samplingUnitId: 0,
        samplingPositionId: "0",
        principalPeople: "",
        samplingPeople: this.$store.getters.name,
        samplingDateTime: null,
        samplingPurpose: "",
        samplingEquipment: "",
        samplingRemark: "",
        creatorId: 0,
        samplingSamples: [],
        // 删除的采样样品
        samplingSamplesDel: [],
        // 默认20已提交
        samplingSingleCode: 20,
      },
      formData: {
        id: 0,
        samplingUnitName: "",
        samplingUnitId: 0,
        samplingPositionId: "0",
        principalPeople: "",
        samplingPeople: this.$store.getters.name,
        samplingDateTime: null,
        samplingPurpose: "",
        samplingEquipment: "",
        samplingRemark: "",
        creatorId: 0,
        samplingSamples: [],
        // 删除的采样样品
        samplingSamplesDel: [],
        // 默认20已提交
        samplingSingleCode: 20,
      },
      formDataRules: {
        samplingSamples: [
          {
            type: "array",
            required: true,
            message: "请添加样品",
            trigger: "blur",
          },
        ],
        samplingUnitName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        samplingUnitId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        samplingPositionId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        principalPeople: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        samplingPeople: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        samplingDateTime: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        samplingPurpose: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        samplingEquipment: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        samplingRemark: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        creatorId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
      },
      initErrorMsg: {
        samplingUnitId: "",
        samplingPositionId: "",
        principalPeople: "",
        samplingPeople: "",
        samplingDateTime: "",
        samplingPurpose: "",
        samplingEquipment: "",
        samplingRemark: "",
        creatorId: "",
      },
      errorMsg: {
        samplingUnitId: "",
        samplingPositionId: "",
        principalPeople: "",
        samplingPeople: "",
        samplingDateTime: "",
        samplingPurpose: "",
        samplingEquipment: "",
        samplingRemark: "",
        creatorId: "",
      },
    };
  },
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    this.options = [];
    this.options.unshift({
      id: "0",
      position: "请选择",
    });
    if (this.editId) {
      get({ id: this.editId }).then((res) => {
        this.formData = res.data;
        this.formData.samplingSamples.forEach((element) => {
          this.sampleNum.push(element.samplingSampleNum);
        });
        this.initData = res.data;
        // 查询采样地点
        // getListNoPage({ id: res.data.samplingUnitId }).then((res) => {
        //   this.options = res.data;
        //   this.options.unshift({
        //     id: "0",
        //     position: "请选择",
        //   });
        //   console.log(this.options);
        // });
      });
    }
  },
  methods: {
    // 草稿保存
    draftSubmit: _.throttle(function() {
      if (this.submitLoad) {
        this.submitLoad = false;
        this.formData.samplingSingleCode = 10;

        // 判断被采样单位名称是否更改了更改了就清空被采样单位id
        if (this.formData.samplingUnitName !== this.unitName) {
          this.formData.samplingUnitId = 0;
        }

        this.Savedrafts("formData");
      }
    }, 2000),
    submit: _.throttle(function() {
      if (this.submitLoad) {
        this.submitLoad = false;

        this.formData.samplingSingleCode = 20;
        // 判断被采样单位名称是否更改了更改了就清空被采样单位id
        if (this.formData.samplingUnitName !== this.unitName) {
          this.formData.samplingUnitId = 0;
        }
        this.onSubmit("formData");
      }
    }, 2000),
    // 样品编号改变事件
    samplingSampleNumChange(index, value) {
      // 新增的样品数据需要state状态,编辑的数据不需要
      if (
        value === this.sampleNum[index].num &&
        String(this.formData.samplingSamples[index].id) === "0"
      ) {
        this.formData.samplingSamples[index].state = 1;
      } else if (String(this.formData.samplingSamples[index].id) === "0") {
        this.formData.samplingSamples[index].state = 0;
      }
    },
    // 关闭选择采样单位方法
    colseSamplingSample(row) {
      this.formData.samplingUnitName = row.unitName;
      this.unitName = row.unitName;
      this.formData.samplingUnitId = row.id;
      // // 查询采样地点
      // getListNoPage({ id: row.id }).then((res) => {
      //   console.log(res.data);
      //   this.options = res.data;
      //   this.options.unshift({
      //     id: 0,
      //     position: "请选择",
      //   });
      // });
    },
    // 删除采样样品
    delSamplingSample(index) {
      if (this.formData.samplingSamplesDel === null) {
        this.formData.samplingSamplesDel = [];
      }
      if (this.formData.samplingSamples[index].id !== 0) {
        this.formData.samplingSamplesDel.push(
          this.formData.samplingSamples[index]
        );
      }
      this.formData.samplingSamples.splice(index, 1);
      this.sampleNum.splice(index, 1);
    },
    // 新增采样样品
    addSamplingSample() {
      if (this.formData.samplingSamples === null) {
        this.formData.samplingSamples = [];
      }
      this.formData.samplingSamples.push({
        id: "0",
        samplingSampleNum: "",
        smaplingSampleName: "",
        samplingSampleCount: 0,
        // 是否使用了编号规则生成的编号，默认0未使用1使用
        state: 0,
      });
      // 是否根据编号生成后续编号判断
      // var state = false;
      // var newNum = "";
      // for (let i = this.formData.samplingSamples.length - 1; i >= 0; i--) {
      //   if (this.formData.samplingSamples[i].state === 1) {
      //     newNum = this.formData.samplingSamples[i].samplingSampleNum;
      //     // state = true;
      //     break;
      //   }
      // }
      // 采样单新增样品生成编号
      // if (state) {
      //   GetSamplingSampleNumByNewNum({ newNum: newNum })
      //     .then((res) => {
      //       if (res.code === 200) {
      //         this.formData.samplingSamples[
      //           this.formData.samplingSamples.length - 1
      //         ].samplingSampleNum = res.data[0];
      //         this.formData.samplingSamples[
      //           this.formData.samplingSamples.length - 1
      //         ].state = 1;
      //       } else {
      //         this.$message(res.data.msg);
      //       }
      //     })
      //     .catch(() => {});
      // } else {
      //   GetSamplingSampleNum({})
      //     .then((res) => {
      //       if (res.data.code === 200) {
      //         this.formData.samplingSamples[
      //           this.formData.samplingSamples.length - 1
      //         ].samplingSampleNum = res.data.data;
      //         this.formData.samplingSamples[
      //           this.formData.samplingSamples.length - 1
      //         ].state = 1;
      //       } else {
      //         this.$message(res.data.msg);
      //       }
      //     })
      //     .catch(() => {});
      // }

      // 把生成的样品编号和下标存入sampleNum，用于判断编号是否改变
      if (this.sampleNum === null || this.sampleNum.length === 0) {
        this.sampleNum = [];
      }
      this.sampleNum.push({
        index: this.formData.samplingSamples.length - 1,
        num: this.formData.samplingSamples[
          this.formData.samplingSamples.length - 1
        ].samplingSampleNum,
      });
    },
    addUnit() {
      this.chioceDialogVisible = true;
    },
    cancel() {
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogFormVisible", false);
    },
    closeDialog() {
      this.sampleNum = [];
      this.$refs["formData"].resetFields();
      this.$emit("update:readOnly", false);
      this.$emit("update:editId", "");
      this.$parent.getList();
      this.cancel();
    },
    Savedrafts() {
      if (this.formData.id <= 0) {
        create(this.formData)
          .then((res) => {
            if (res.code === 200) {
              this.closeDialog();
              this.submitLoad = true;
            } else {
              this.showValidateMsgCheck(res);
              this.submitLoad = true;
            }
            this.loading = false;
          })
          .catch(() => {
            this.submitLoad = true;

            this.loading = false;
          });
      } else {
        update(this.formData)
          .then((res) => {
            if (res.code === 200) {
              this.closeDialog();
              this.submitLoad = true;
            } else {
              this.showValidateMsgCheck(res);
              this.submitLoad = true;
            }
            this.loading = false;
            this.submitLoad = true;
          })
          .catch(() => {
            this.loading = false;
            this.submitLoad = true;
          });
      }
    },
    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          if (this.formData.id <= 0) {
            create(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                  this.submitLoad = true;
                } else {
                  this.showValidateMsgCheck(res);
                  this.submitLoad = true;
                }
                this.loading = false;
                this.submitLoad = true;
              })
              .catch(() => {
                this.loading = false;
                this.submitLoad = true;
              });
          } else {
            update(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                  this.submitLoad = true;
                } else {
                  this.showValidateMsgCheck(res);
                  this.submitLoad = true;
                }
                this.loading = false;
                this.submitLoad = true;
              })
              .catch(() => {
                this.loading = false;
                this.submitLoad = true;
              });
          }
        } else {
          return false;
        }
      });
    },
    // 判断输入内容
    blurTexts(e) {
      const boolean = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!boolean) {
        this.$message.warning("请输入正整数");
        e.target.value = "";
      }
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("samplingUnitId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "samplingPositionId",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("principalPeople", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("samplingPeople", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("samplingDateTime", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("samplingPurpose", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "samplingEquipment",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("samplingRemark", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creatorId", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.addCustomer {
  width: 30px;
  color: white;
  font-size: 20px;
  height: 32px;
  text-align: center;
  border-radius: 5px;
  border: 1px silver;
  background-color: #4787ff;
  position: absolute;
  top: 0px;
  right: 0px;
}
</style>
